var cfg = require('../../utils/cfg');
var socketUtil = require('../../utils/socketUtil');

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showTopic : true,
    paperInfo : {},
    topic : {},
    topicArray : [],
    playNum : '',
    roomTicket : '',
    openId : '',
    checked : false,
    totalTopic : 0,
    endNum : 1,
    fromType : 0,
    model : 0,
    doubleDo : false,
    deadNum : 7,
    timeWaitFun : {},
    hasFinished : false,
    answeredData : []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('fromType=' + options.fromType);
    this.data.fromType = options.fromType;
    this.data.model = options.model;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    let paperData = wx.getStorageSync('paperInfo');

    let paperInfo = paperData.data.paper;
    let playNum = paperData.data.playNum;
    let roomTicket = paperData.data.roomTicket;
    let openId = paperData.data.openId;
    let topicArray = paperInfo.topics;
    this.data.topicArray = topicArray;

    this.setData({
      paperInfo: paperInfo,
      playNum: playNum,
      roomTicket: roomTicket,
      openId: openId,
      totalTopic: topicArray.length,
      topic: topicArray.pop()
    })

    let that = this;
    that.data.timeWaitFun = setInterval(function () {

      console.log('>>>>>>>答题定时器');
      let deadNum = that.data.deadNum;
      if (deadNum <= 0)  {
        console.log('>>>>>>>作答超时 积分清零');

        //TODO 木有做完 则本房间所有人积分清零
        that.zerojifen();
       // that.nextWj();

        that.setData({
          deadNum: 7
        })

        return;
      }
      that.setData({
        deadNum: --deadNum
      })

    }, 1000);

  },

  zerojifen : function() {
    let that = this;
    clearInterval(that.data.timeWaitFun);

    wx.request({
      url: cfg.host + cfg.mwurl.zerojifen,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket')
      },
      success: function (res) {
        wx.showModal({
          title: '提示',
          showCancel : false,
          content: '作答超时，积分清零',
          success: function (res) {
            if (res.confirm) {
              //进入下一轮
              wx.reLaunch({
                url: '/pages/home/home'
              })
            }
          }
        })
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  radioChange : function(event) {

    let that = this;
    if (that.data.doubleDo) {
      console.log('>>>>>>double do some things');
        return;
    }

    console.log('选择了' + that.data.topicArray.length);
    let optionId = event.detail.value;
    console.log('optionId=' + optionId);
    console.log('paperId=' + that.data.paperInfo.id);

    that.data.doubleDo = true;

    let innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.autoplay = true;
    innerAudioContext.src = '/images/1.mp3';
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    });

    innerAudioContext.onEnded(()=>{
      console.log('播放结束');
    });


    //用户作答
    wx.request({
      url: cfg.host + cfg.mwurl.paperAnswer,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        paperId: that.data.paperInfo.id,
        topicId: that.data.topic.id,
        optionId: optionId,
        playNum: that.data.playNum
      },
      success: function (res) {
        console.log(res.data);
        //如果回答完毕 则通知所有人 然后跳转到默契页面
        that.zuodawanbi();
      },
      complete : function() {
        setTimeout(function () {
          that.nextWj();
          that.setData({
            deadNum: 7
          })

        }, 100)

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })



  },

  zuodawanbi : function() {
    let that = this;
    if (that.data.topicArray.length <= 0) {
      clearInterval(that.data.timeWaitFun);

      if (that.data.hasFinished) {
          return;
      }

      that.data.hasFinished = true;

      that.loadListAnswered();

    }
  },

  tiaozhuan : function() {
    let that = this;
    if (that.data.fromType == 10) {
      console.log(">>>paperId=" + that.data.paperInfo.id);
      wx.reLaunch({
        url: '/pages/tacit/tacit?model=' + that.data.model + '&paperId=' + that.data.paperInfo.id
      })
    }

    if (that.data.fromType == 11) {
      console.log(">>>paperId=" + that.data.paperInfo.id);
      wx.reLaunch({
        url: '/pages/tacitOther/tacitOther?model=' + that.data.model + '&paperId=' + that.data.paperInfo.id
      })
    }

    if (that.data.fromType == 12) {
      console.log(">>>paperId=" + that.data.paperInfo.id);
      wx.reLaunch({
        url: '/pages/moreTacit/moreTacit?model=' + that.data.model + '&paperId=' + that.data.paperInfo.id
      })
    }

    if (that.data.fromType == 13) {
      console.log(">>>paperId=" + that.data.paperInfo.id);
      wx.reLaunch({
        url: '/pages/moreTacitOther/moreTacitOther?model=' + that.data.model + '&paperId=' + that.data.paperInfo.id
      })
    }
  },

  nextWj : function() {
    let that = this;
    if (that.data.topicArray.length <= 0) {
      that.zuodawanbi();
      return;
    }

    that.setData({
      topic: that.data.topicArray.pop(),
      checked: false,
      endNum: that.data.endNum >= that.data.totalTopic ? that.data.totalTopic : that.data.endNum + 1
    })

    that.data.doubleDo = false;
  },

  loadListAnswered : function() {
    let that = this;
    wx.request({
      url: cfg.host + cfg.mwurl.listAnswered,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        playNum: that.data.playNum
      },
      success: function (res) {
        let answeredData = res.data.data;
        that.setData({ showTopic: false, answeredData: answeredData});
        
        setTimeout(function () { that.tiaozhuan(); }, 3000);
      },
      complete: function () {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.globalData.socketCallBack = this.doSocket;
  },

  doSocket : function(res) {
    console.log('ready socket ' + res);
    let that = this;
    let wsDTO = res

    if (1008 === wsDTO.wsType) {
      clearInterval(that.data.timeWaitFun);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})